let userId, doctorIcon, memberId, memberData, twid, nickName, headImg;

var doctorId = $.cookie("doctorId");
var serverIP = "";
var serverApi = "";
var serverApi3 = "";
var serverApi1 = "";
var socketUrl6 = "";
//菜单点击事件
$(document).ready(function () {
    $("#record").css("display", "block");
    $("a.tab-style").click(function () {
        var ss = $(this);
        $("a.tab-style").removeClass("select");
        ss.addClass("select");

        $("div.full-page").css("display", "none");
        let select = ss.attr("sid");
        console.log("select id: ", select);
        $(select).css("display", "block");
    });
    doctorIcon = $.cookie("icon");
    memberId = $.cookie("memberId");
    memberData = JSON.parse(sessionStorage.getItem('memberData'));
    findChatList = JSON.parse(sessionStorage.getItem('findChatList'));
    console.log("===========")
    console.log("===========")
    console.log("===========")
    console.log("===========")
    console.log("===========")
    console.log(findChatList)
    console.log("===========")
    console.log("===========")
    console.log("===========")
    console.log("===========")
    console.log("===========")
    twid = findChatList.twid;
    doctorId = findChatList.doctorId;
    userId = doctorId;
    nickName = $.cookie("truename");
    headImg = $.cookie("icon");
    serverIP = findChatList.serverIP;
    serverApi = findChatList.serverApi;
    serverApi3 = findChatList.serverApi3;
    serverApi1 = findChatList.serverApi1;
    socketUrl6 = findChatList.socketUrl6;
    //加载历史聊天记录
    f1();
    //初始化socket
    loadSocket();
    window.setInterval(function () {
        send1();
    }, 2000);//每2秒发一下ms11保持socket连接
});

// //发送图片
// function tuPian() {
//     layer.msg("ffff")
// }

//时间格式化
Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//开具处方
function chuFang() {
    sessionStorage.removeItem("twShowChuFangId")
    layer.open({
        title: "开具处方",
        type: 2,
        area: ["590px", "660px"],
        content: "page/diagnose/doctors_advice.html",
        shadeClose: true,
        end: function () {
            //图文还是视频
            if (sessionStorage.getItem("twShowChuFangId")) {
                var message = "#ms12#m" + memberId + "#ms12#d" + doctorId + "#ms12#" + nickName + "#ms12#" + headImg + "#ms12#" + "图文开处方" + "#ms12#" + 6 + "#ms12#" + twid + "#ms12#";
                if (!window.WebSocket) {
                    console.error("socket连接失败..");
                    return;
                }
                if (socket.readyState == WebSocket.OPEN) {
                    socket.send(message);
                    // layer.msg("您已成功向 " + $("#merName").text() + " 开具处方");
                    // layer.close(fwbIndex);
                } else {
                    console.error("socket连接失败请重试..");
                }
            }
            $("#chatList").prepend('\n' +
                '\t\t\t\t\t<div class="flex flex-row j-end" style="margin-top: 15px;margin-bottom: 15px;margin-right: 20px;height: auto;">\n' +
                '\t\t\t\t\t\t<div class="flex flex-column a-end">\n' +
                '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + $.cookie("truename") + '&nbsp;' + new Date().Format("yyyy-MM-dd hh:mm:ss") + '" style="font-size: 12px;color: #989898;text-align: end;margin-right: 14px;width:160px"></input>\n' +
                '\t\t\t\t\t\t\t<div class="flex flex-row" style="margin-right: 5px;">\n' +
                '\t\t\t\t\t\t\t\t<div class="flex flex-wrap a-center" style="font-size: 16px; color: #333333;min-width: 50px;max-width: 350px;height: auto; min-height: 20px;background: #B2D3FF;\n' +
                '\t\t\t\t\t\t\t\t\t\tborder-radius: 5px;text-align: center;padding: 10px;margin-top: 5px;">已给患者开具处方，<span style="color: #01AAED" onclick="chuFangDetail(' + sessionStorage.getItem("twShowChuFangId") + ')">点击查看</span></div>\n' +
                '\t\t\t\t\t\t\t\t<img src="img/chat/chat_right_arrows.png" style="width: 13px;height: 15px;margin-top: 10px;" />\n' +
                '\t\t\t\t\t\t\t</div>\n' +
                '\t\t\t\t\t\t</div>\n' +
                '\t\t\t\t\t\t<img src="' + doctorIcon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                '\t\t\t\t\t</div>')
        }
    });
}

function chuFangDetail(orderId) {
    $.cookie('tempId', orderId, {path: '/'});
    index = layui.layer.open({
        title: "处方详情",
        type: 2,
        area: ["600px", "600px"],
        content: "page/diagnose/inquiry_history_02.html",
        shadeClose: true,
        success: function () {
        }
    });
}

//开具医技
function yiJi() {
    layer.msg("ffff")
}

//服务包
function fuWuBao() {
    layer.msg("ffff")
}

//开具建议
function jianYi() {
    sessionStorage.removeItem("twShowJianYiId")
    layer.open({
        title: "开具建议",
        type: 2,
        area: ["590px", "660px"],
        content: "page/diagnose/issued_suggest.html",
        shadeClose: true,
        // success: function () {
        //     sessionStorage.setItem('look1Data', JSON.stringify(data));
        // },
        end: function () {
            //图文还是视频
            if (sessionStorage.getItem("twShowJianYiId")) {
                var message = "#ms12#m" + memberId + "#ms12#d" + doctorId + "#ms12#" + nickName + "#ms12#" + headImg + "#ms12#" + "图文开建议" + "#ms12#" + 24 + "#ms12#" + twid + "#ms12#";
                if (!window.WebSocket) {
                    console.error("socket连接失败..");
                    return;
                }
                if (socket.readyState == WebSocket.OPEN) {
                    socket.send(message);
                    // layer.msg("您已成功向 " + $("#merName").text() + " 开具处方");
                    // layer.close(fwbIndex);
                } else {
                    console.error("socket连接失败请重试..");
                }
            }
        }
    });
}

function jianYiDetail(adviseId) {
    $.cookie('tempId', adviseId, {path: '/'});
    index = layui.layer.open({
        title: "建议详情",
        type: 2,
        area: ["600px", "600px"],
        content: "page/diagnose/inquiry_history_03.html",
        shadeClose: true,
        success: function () {
        }
    });
}


function f1() {
    var reqData = {doctorId: doctorId, twid: twid};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/findUmsMemberReceptionDeskTwVO" + "?" + formatParams(reqData),
        success: function (result) {
            if (result.code === 200) {
                let data = result.data;
                f2(data);
            }
        },
        error: function (e) {
            layer.msg("请求失败！");
        }
    });
}

function f2(data) {
    let reqData2 = {
        aid: 'm' + data.memberId,
        bid: 'd' + doctorId,
        zhenid: data.diagnosisId,
        page: 1,
        size: 200
    };
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi3 + "/umsmemberdiagnosis/findChatList" + "?" + formatParams(reqData2),
        success: function (result) {
            console.log("findTwList res: ", result);
            if (result.code === 200) {
                let list = result.data;
                refreshData(list, reqData2.aid);
            }
        }
    })
}

var isShowMore = false;

function onMoreAdd() {
    if (isShowMore) {
        $("#chatMore").hide()
        isShowMore = false;
    } else {
        $("#chatMore").show()
        isShowMore = true;
    }
}

//断开连接
function onSendClose() {
    sessionStorage.setItem('tcpLink', "stop");
    sessionStorage.removeItem("changeLeft")
    sessionStorage.removeItem('memberData');
    $.removeCookie('memberId', {path: '/'});
    $.removeCookie('memberSid', {path: '/'});
    $.ajax({
        type: "POST",
        url: serverApi + "/omsring/updateOmsImageText?twid=" + twid,
        success: function (result) {
            if (result.code === 200) {
                layer.msg("挂断成功！");
            }
        },
        error: function (e) {
            layer.msg("请求失败！");
        }
    });
    setTimeout(function () {
        parent.window.location.reload()
    }, 500)
}

//返回主页
function onSendBack() {
    layer.msg("即将返回主页！");
    sessionStorage.setItem('tcpLink', "stop");
    sessionStorage.removeItem("changeLeft")
    sessionStorage.removeItem('memberData');
    $.removeCookie('memberId', {path: '/'});
    $.removeCookie('memberSid', {path: '/'});
    setTimeout(function () {
        parent.window.location.reload()
    }, 500)
}

function refreshData(data, userId) {
    //获取模板上的HTML
    var heTextHtml = $('script[type="text/chatHeText"]').html();
    var myTextHtml = $('script[type="text/chatMyText"]').html();
    var heImgHtml = $('script[type="text/chatHeImg"]').html();
    var myImgHtml = $('script[type="text/chatMyImg"]').html();
    //定义一个数组，用来接收格式化合的数据
    var arr = [];
    //对数据进行遍历
    $.each(data, function (i, o) {
        //这里取到o就是上面rows数组中的值, formatTemplate是最开始定义的方法.
        let item = {};
        item.icon = $.cookie("icon");
        item.time = $.cookie("truename") + '&nbsp;' + o.createTime;
        item.message = o.content;
        item.image = o.content;
        if (userId != o.aid) {
            item.icon = memberData.icon;
            item.time = memberData.name + '&nbsp;' + o.createTime;
            if (o.type == 1) {
                arr.push(formatTemplate(item, heTextHtml));
            } else if (o.type == 2) {
                arr.push(formatTemplate(item, heImgHtml));
            }
        } else {
            item.icon = o.ahead;
            item.time = o.aname + '&nbsp;' + o.createTime;
            if (o.type == 1) {
                arr.push(formatTemplate(item, myTextHtml));
            } else if (o.type == 2) {
                arr.push(formatTemplate(item, myImgHtml));
            }
        }
    });
    // 数组倒序
    arr.reverse();
    $('#chatList').empty();
    $('#chatList').append(arr.join(''));
}

function onSendMsg() {
    let message = $('#chatInput').val();
    if (!isNullOrEmpty(message)) {
        send($.cookie("truename"), $.cookie("icon"), message, memberData.diagnosisId)
        //清空输入框
        $('#chatInput').val("");
    }
}

function onSelectImage(files) {
    console.log("files: ", files);
    if (!files || !files[0]) {
        return;
    }
    var selectFile = files[0];
    var imageType = /^image\//;
    if (!imageType.test(selectFile.type)) {
        console.log("not image");
        return;
    }
    var reader = new FileReader();
    reader.onload = function (evt) {
        var image = evt.target.result;
        var user = getUserInfo();
        let item = {};
        item.icon = user.icon;
        item.time = new Date().Format("yyyy-MM-dd HH:mm:ss");
        item.image = image;
        var chatMyImg = $('script[type="text/chatMyImg"]').html();
        $('#chatList').prepend(formatTemplate(item, chatMyImg));
    }
    reader.readAsDataURL(selectFile);
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function getTestDada() {
    return [{
        icon: 'img/login_bg.jpg',
        type: 1,
        aid: 'm124',
        time: '2021-03-27 17:10:05',
        message: '医生，您好，我把图片发给您了',
        image: 'img/login_bg.jpg'
    }, {
        icon: 'img/login_bg.jpg',
        type: 2,
        aid: 'm124',
        time: '2021-03-27 17:10:05',
        message: '医生，您好，我把图片发给您了',
        image: 'img/login_bg.jpg'
    },
    ];
}

// $("#chatList div img").click(function(e){
//     console.log(e.target)
//     console.log(this)
//     alert("rrrwerqw")
// })

function toLarge(data) {
    console.log(data)

    parent.parent.layer.open({
        type: 1,
        title: "图片",
        // maxmin: true,
        area: ["600px", "600px"],
        content: '<img style="width:100%;height:auto;" src="' + data.src + '">',
        shadeClose: true,
    });

}

/***Socket连接开始***/
var socket = "";

function loadSocket() {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket(socketUrl6);
        socket.onmessage = function (event) {
            var data = event.data;
            console.log("收到消息：" + data);
            if (data.indexOf("#ms11#") != -1) {
                //发送初始化验证消息
            } else if (data.indexOf("#ms12#") != -1) {
                //发送文字消息 #ms12#aid#ms12#bid#ms12#uname#ms12#uhead#ms12#content#ms12#type#ms12#time#ms12#
                //type：1发文字,2发图片,3发视频文件,4发位置,5发服务包,6发处方,7发医生视频链接,8挂断提醒,11暂停视频,12暂停恢复,13拒绝视频,
                //      14预约确认,15开了处方,16护士通知患者支付,17保存服务包id,21开了检查单,24图文开了建议
                var res = data.substr(data.indexOf("#ms12#"), data.length).split("#ms12#");
                var name = res[3];
                var head = res[4];
                //var txt = to_html(res[5]).replace(/\[:(.+?)\]/g,'<img src="../img2/$1.gif"/>');
                //txt = txt.replace(/\[img:(.+?)\]/g,'<img src="$1" style="width:107px;" onclick="to_img1(this)"/>');
                //txt = txt.replace(/\[video:(.+?)\]/g,'<img src="../img2/black2.png" surl="$1" style="width:110px;height:80px;" onclick="to_video1(this)"/>');
                var content1 = res[5];
                var time = res[res.length - 2];
                var type = res[6];
                if (head == "") head = "image/head1.jpg";
                var str = "";
                if (("d" + userId) == res[2]) {
                    //我发出的消息
                    if (type == "2") {
                        $("#chatList").prepend('<div class="flex flex-row j-end" style="height: auto;margin-top: 15px;margin-bottom: 15px;margin-right: 20px;">\n' +
                            '\t\t\t\t\t\t<div class="flex flex-column a-end">\n' +
                            '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;text-align: end;margin-right: 14px;"></input>\n' +
                            '\t\t\t\t\t\t\t<img onclick="toLarge(this)" src="' + content1 + '" style="width: auto;height: 100px;margin-top: 5px;margin-right: 14px;" />\n' +
                            '\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t<img src="' + doctorIcon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                            '\t\t\t\t\t</div>')
                    } else if (type == "6") {
                        // alert("rrrrr")
                        // $("#chatList").prepend('\n' +
                        //     '\t\t\t\t\t<div class="flex flex-row j-end" style="margin-top: 15px;margin-bottom: 15px;margin-right: 20px;height: auto;">\n' +
                        //     '\t\t\t\t\t\t<div class="flex flex-column a-end">\n' +
                        //     '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;text-align: end;margin-right: 14px;width:160px"></input>\n' +
                        //     '\t\t\t\t\t\t\t<div class="flex flex-row" style="margin-right: 5px;">\n' +
                        //     '\t\t\t\t\t\t\t\t<div class="flex flex-wrap a-center" style="font-size: 16px; color: #333333;min-width: 50px;max-width: 350px;height: auto; min-height: 20px;background: #B2D3FF;\n' +
                        //     '\t\t\t\t\t\t\t\t\t\tborder-radius: 5px;text-align: center;padding: 10px;margin-top: 5px;">已给患者开具处方，<span style="color: #01AAED" onclick="chuFangDetail(' + sessionStorage.getItem("twShowChuFangId") + ')">点击查看</span></div>\n' +
                        //     '\t\t\t\t\t\t\t\t<img src="img/chat/chat_right_arrows.png" style="width: 13px;height: 15px;margin-top: 10px;" />\n' +
                        //     '\t\t\t\t\t\t\t</div>\n' +
                        //     '\t\t\t\t\t\t</div>\n' +
                        //     '\t\t\t\t\t\t<img src="' + doctorIcon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                        //     '\t\t\t\t\t</div>')
                    } else if (type == "24") {
                        $("#chatList").prepend('\n' +
                            '\t\t\t\t\t<div class="flex flex-row j-end" style="margin-top: 15px;margin-bottom: 15px;margin-right: 20px;height: auto;">\n' +
                            '\t\t\t\t\t\t<div class="flex flex-column a-end">\n' +
                            '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;text-align: end;margin-right: 14px;width:160px"></input>\n' +
                            '\t\t\t\t\t\t\t<div class="flex flex-row" style="margin-right: 5px;">\n' +
                            '\t\t\t\t\t\t\t\t<div class="flex flex-wrap a-center" style="font-size: 16px; color: #333333;min-width: 50px;max-width: 350px;height: auto; min-height: 20px;background: #B2D3FF;\n' +
                            '\t\t\t\t\t\t\t\t\t\tborder-radius: 5px;text-align: center;padding: 10px;margin-top: 5px;">已给患者开具建议，<span style="color: #01AAED" onclick="jianYiDetail(' + sessionStorage.getItem("twShowJianYiId") + ')">点击查看</span></div>\n' +
                            '\t\t\t\t\t\t\t\t<img src="img/chat/chat_right_arrows.png" style="width: 13px;height: 15px;margin-top: 10px;" />\n' +
                            '\t\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t<img src="' + doctorIcon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                            '\t\t\t\t\t</div>')
                    } else if (type != "15") {
                        $("#chatList").prepend('\n' +
                            '\t\t\t\t\t<div class="flex flex-row j-end" style="margin-top: 15px;margin-bottom: 15px;margin-right: 20px;height: auto;">\n' +
                            '\t\t\t\t\t\t<div class="flex flex-column a-end">\n' +
                            '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;text-align: end;margin-right: 14px;width:160px"></input>\n' +
                            '\t\t\t\t\t\t\t<div class="flex flex-row" style="margin-right: 5px;">\n' +
                            '\t\t\t\t\t\t\t\t<div class="flex flex-wrap a-center" style="font-size: 16px; color: #333333;min-width: 50px;max-width: 350px;height: auto; min-height: 20px;background: #B2D3FF;\n' +
                            '\t\t\t\t\t\t\t\t\t\tborder-radius: 5px;text-align: center;padding: 10px;margin-top: 5px;">' + content1 + '</div>\n' +
                            '\t\t\t\t\t\t\t\t<img src="img/chat/chat_right_arrows.png" style="width: 13px;height: 15px;margin-top: 10px;" />\n' +
                            '\t\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t<img src="' + doctorIcon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                            '\t\t\t\t\t</div>')
                    }
                } else {
                    //对方发给我的消息
                    if (type == "2") {
                        $("#chatList").prepend('\n' +
                            '\t\t\t\t\t<div class="flex flex-row" style="height: auto;margin-top: 15px;margin-bottom: 15px;margin-left: 20px;">\n' +
                            '\t\t\t\t\t\t<img src="' + memberData.icon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                            '\t\t\t\t\t\t<div class="flex flex-column">\n' +
                            '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;\n' +
                            '\t\t\t\t\t\t\t\tmargin-left: 14px;"></input>\n' +
                            '\t\t\t\t\t\t\t<img onclick="toLarge(this)" src="' + content1 + '" style="width: 100px;height: 100px;margin-top: 5px;margin-left: 14px;" />\n' +
                            '\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t</div>')
                    } else {
                        $("#chatList").prepend('\n' +
                            '\t\t\t\t\t<div class="flex flex-row" style="height: auto;margin-top: 15px;margin-bottom: 15px;margin-left: 20px;">\n' +
                            '\t\t\t\t\t\t<img src="' + memberData.icon + '" style="width: 40px;height: 40px;border-radius: 5px;" />\n' +
                            '\t\t\t\t\t\t<div class="flex flex-column">\n' +
                            '\t\t\t\t\t\t\t<input class="clear-bg" type="text" disabled="true" value="' + name + '&nbsp;' + time + '" style="font-size: 12px;color: #989898;\n' +
                            '\t\t\t\t\t\t\t\tmargin-left: 14px;width:160px"></input>\n' +
                            '\t\t\t\t\t\t\t<div class="flex flex-row" style="margin-left: 5px;">\n' +
                            '\t\t\t\t\t\t\t\t<img src="img/chat/chat_left_arrows.png" style="width: 13px;height: 15px;margin-top: 10px;" />\n' +
                            '\t\t\t\t\t\t\t\t<div class="flex flex-wrap a-center" style="font-size: 16px; color: #333333;min-width: 50px;max-width: 350px; min-height: 20px;background: #E6E6E6;\n' +
                            '\t\t\t\t\t\t\t\t\t\tborder-radius: 5px;text-align: center;padding: 10px;margin-top: 5px;">' + content1 + '</div>\n' +
                            '\t\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t\t</div>\n' +
                            '\t\t\t\t\t</div>')
                    }
                    // //对方发给我的消息
                    // if (type == "1" || type == "2" || type == "6") {
                    //     str += "<div class='chat-left'>";
                    //     str += "<div class='chat-left-headimg'><img src='" + head + "' sid='" + memberId + "'></div>";
                    //     str += "<div class='chat-left-time'>" + name + "&nbsp;&nbsp;" + time + "</div>";
                    //     str += "<div class='chat-left-text'>";
                    //     if (type == "1") str += "<i></i><p>" + content1 + "</p>";
                    //     else if (type == "2") str += "<img src=" + content1 + " class=imgmsg onclick='toFdImg(this)'/>";
                    //     else if (type == "6") str += "<i></i><p>处方已开<span class=bold onclick='kanchufang(" + content1 + ")'>【双击查看】</span></p>";
                    //     str += "</div></div>";
                    // }
                }
                $("#chatList").append(str);
                $("#chatList")[0].scrollTop = $("#chatList")[0].scrollHeight;
            }
        };
        socket.onopen = function (event) {

        };
        socket.onclose = function (event) {

        };
    }
}


function send1() {
    var message = "#ms11#m" + memberId + "#ms11#d" + userId + "#ms11#";//验证消息
    if (!window.WebSocket) {
        layer.msg("图文连接失败.");
        return;
    }
    //alert(JSON.stringify(socket));
    if (socket != "" && socket.readyState == WebSocket.OPEN) {
        socket.send(message);
    } else {
        layer.msg("网络连接失败请重试.");
    }
}

function send(nickName, headImg, message, diagnosisId) {
    // var message = $("#faArea").val();//普通消息 #ms12#aid#ms12#bid#ms12#uname#ms12#uhead#ms12#content#ms12#type#ms12#zhenid#ms12#
    message = message.replace(/\r\n/ig, "<br>").replace(/\n/ig, "<br>").replace(/\s/gi, '&nbsp;');
    if (message != "") {
        message = "#ms12#m" + memberId + "#ms12#d" + userId + "#ms12#" + nickName + "#ms12#" + headImg + "#ms12#" + message + "#ms12#" + 1 + "#ms12#" + diagnosisId + "#ms12#";
        if (!window.WebSocket) {
            layer.msg("图文连接失败..");
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
            $("#faArea").val("");
        } else {
            layer.msg("网络连接失败请重试..");
        }
    } else {
        layer.msg("说点什么吧！");
    }
    //其他按钮回复原状

}

function to_html(v) {
    //var reg = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
    //v = v.replace(reg, "<a href='$1$2' style='color:#00A2E8;text-decoration:underline;'>$1$2</a>");
    return v;
}

//放大显示图片
function toFdImg(s) {
    layer.open({
        type: 1,
        shade: false,
        title: false,
        area: ['1140px', '600px'],
        content: '<img src="' + $(s).attr("src") + '" style="width:1140px;" />',
        cancel: function () {

        }
    });
}

/***Socket连接结束***/

layui.use('upload', function () {
    var upload = layui.upload;

    //封面图上传
    const uploadInst = upload.render({
        elem: '#test1'
        , url: host + '/a03/umsmember/uploadImage'
        , method: 'post'  //可选项。HTTP类型，默认post
        , field: 'multipartFile'
        , done: function (res) {
            //如果上传失败
            if (res.code !== 200) {
                return layer.msg('上传失败');
            } else {
                //上传成功
                loadSocket();
                window.setTimeout(function () {
                    var message = "#ms12#m" + memberId + "#ms12#d" + userId + "#ms12#" + $.cookie("truename") + "#ms12#" + $.cookie("icon") + "#ms12#" + res.data + "#ms12#" + 2 + "#ms12#" + memberData.diagnosisId + "#ms12#";
                    if (!window.WebSocket) {
                        layer.msg("图文连接失败..");
                        return;
                    }
                    if (socket.readyState == WebSocket.OPEN) {
                        socket.send(message);
                    } else {
                        layer.msg("图文连接失败请重试..");
                    }
                }, 900);
            }
        }
    });
});